package com.jsm.twentyfour.service;

import com.alibaba.fastjson.JSONObject;
import com.jsm.twentyfour.reponse.WechatSnsResponse;
import com.jsm.twentyfour.util.HttpUtil;
import org.springframework.stereotype.Service;


@Service
public class WechatService {


    private final String appId = "wxd665542445a4e7d8";
    private final String secret = "a3028510b7f85708b436ccf02273a756";

    public WechatSnsResponse oauth2GetOpenid(String code) {

        // 授权（必填）
        String grant_type = "authorization_code";
        //URL
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        // 请求参数
        String params = "appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=" + grant_type;
        // 发送请求
        String data = HttpUtil.get(requestUrl, params);
        System.out.println(data);
        // 解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(data);
        // 用户的唯一标识（openid）
        String Openid = String.valueOf(json.get("openid"));
        String unionid = String.valueOf(json.get("unionid"));
        String session_key = String.valueOf(json.get("session_key"));
        Integer errcode = json.getInteger("errcode");
        String errmsg = String.valueOf(json.get("errmsg"));

        WechatSnsResponse wsRsp = new WechatSnsResponse();
        if (errcode != null) {
            wsRsp.setResult(errcode);
            wsRsp.setErrMsg(errmsg);
        } else {
            wsRsp.setOpenid(Openid);
            wsRsp.setSession_key(session_key);
            wsRsp.setUnionid(unionid);
        }

        return wsRsp;
    }
}
